import pymysql
class A:
    def __init__(self,host,user,password,database,port=3306,charset='utf8'):
        self.host=host
        self.user=user
        self.password=password
        self.database=database
        self.port=port
        self.charset=charset
    def update(self,sql,date):
        db=pymysql.connect(
            host=self.host,
            user=self.user,
            password=self.password,
            database=self.database,
            port=self.port,
            charset=self.charset
        )
        try:
            with db.cursor() as cursor:
                cursor.execute(sql,date)
                db.commit()
                print('数据库操作成功')
        except Exception as e:
            print('更新失败',e)
        finally:
            db.close()
    def select(self,sql):
        a=pymysql.connect(
            host=self.host,
            user=self.user,
            password=self.password,
            database=self.database,
            port=self.port,
            charset=self.charset
        )
        try:
            with a.cursor() as cursor:
                cursor.execute(sql)
                result = cursor.fetchall()
                print(result)
        except Exception as e:
            print('查询失败',e)
        finally:
            a.close()
sbs=A('localhost','root','1234','jiangsu')
b='create table if not exists person(username varchar(20),age int,sex char(4),high double(3,2))'
i=1
while i <= 10:
    b=i+9
    c=1.65 + i * 0.01
    data=str(i)
    a = (f'张{data}',b,'男',c)
    sql = 'insert into person values(%s,%s,%s,%s)'
    sbs.update(sql, a)
    i += 1
sbs.select('select * from person')
sbs.update("update person set sex=%s",('女'))
sbs.select('select * from person')
sbs.update("delete from person",None)


